package com.eunion.web.cms.entity.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.eunion.web.cms.entity.UniversitySetMajor;

public class UniversitySetMajorSpec {
	public static Specification<UniversitySetMajor> build(UniversitySetMajor queryBean) {
		return new UniversitySetMajorQuery(queryBean);
	}

	public static Specification<UniversitySetMajor> build(UniversitySetMajor queryBean,boolean accurate) {
		return new UniversitySetMajorQuery(queryBean,accurate);
	}

	private static class UniversitySetMajorQuery implements Specification<UniversitySetMajor> {

		private boolean accurate = false;
		private UniversitySetMajor queryBean;

		private UniversitySetMajorQuery(UniversitySetMajor queryBean) {
			this.queryBean = queryBean;
		}

		private UniversitySetMajorQuery(UniversitySetMajor queryBean,boolean accurate) {
			this.queryBean = queryBean;
			this.accurate = accurate;
		}

		@Override
		public Predicate toPredicate(Root<UniversitySetMajor> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			List<Predicate> list = getPredicates(root, query, cb, queryBean,accurate);
			Predicate[] preList = new Predicate[list.size()];
			return cb.and(list.toArray(preList));
		}

	}

	private static List<Predicate> getPredicates(Root<UniversitySetMajor> root, CriteriaQuery<?> query, CriteriaBuilder cb,
			UniversitySetMajor queryBean,boolean accurate) {
		// 条件集合
		List<Predicate> list = new ArrayList<>();
		//学校名称
		String universityName = queryBean.getUniversityName();
		//专业代码
		String majorCode = queryBean.getMajorCode();
		//专业名称
		String majorName = queryBean.getMajorName();
		if(accurate) {
			if (StringUtils.isNotBlank(universityName) ) {
				list.add(cb.equal(root.get("universityName"), universityName.trim()));
			} 
			if(StringUtils.isNotBlank(majorCode)) {
				list.add(cb.equal(root.get("majorCode"), majorCode.trim()));
			}
			if(StringUtils.isNotBlank(majorName)) {
				list.add(cb.equal(root.get("majorName"), majorCode.trim()));
			}
		} else {
			
		}
		return list;
	}
}
